<template>
    <van-nav-bar title="编辑商品" left-arrow @click-left="handleLeft" v-if="!showSupplierName">
    </van-nav-bar>
    <div class="add_product" v-if="!showSupplierName">
        <div class="investmentReview_loading" v-if="loadingShow">
            <van-loading />
            <div class="investmentReview_loading_title">加载中...</div>
        </div>
        <van-form @submit="onSubmit" v-if="!loadingShow" validate-first scroll-to-error>
            <van-field name="supplierName" label="供应商名称" v-model="queryParams.supplierName" is-link readonly
                input-align="right" error-message-align="right" placeholder="请选择" :disabled="fiveMechanism"
                @click="popupClcik(() => showSupplierName = true)" required :rules="[
                    { required: true, trigger: 'onBlur', message: '请选择供应商名称' },
                ]" />

            <van-cell-group inset>
                <van-field name="styleName" label="商品名称" v-model="queryParams.styleName"
                    @input="(e) => { forbidRule(e, 'styleName', 'blank') }" placeholder="请输入" input-align="right"
                    :disabled="mechanism || fiveMechanism" error-message-align="right" required maxlength="50" :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入商品名称' },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="productCategoryName" label="商品类目" v-model="queryParams.productCategoryName" is-link
                    readonly input-align="right" error-message-align="right" placeholder="请选择"
                    @click="popupClcik(() => show = true)" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择商品类目' },
                    ]" />
                <div class="cascaderShade" v-if="cascaderShade"></div>
                <van-popup v-model:show="show" round position="bottom">
                    <van-cascader v-model="cascaderValue" title="请选择商品类目" :options="options" @close="show = false"
                        @finish="onFinish" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="brandName" label="品牌" v-model="queryParams.brandName"
                    :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'" input-align="right"
                    error-message-align="right" maxlength="50" :disabled="mechanism || fiveMechanism" :rules="[
                        { required: false, trigger: 'onBlur', message: '请输入品牌名称' },
                        {
                            validator: validatorNumberBrand,
                            message: '请输入正确的品牌名称',
                        },
                    ]" />
            </van-cell-group>
            <formNumberKeyboard :formRef="formRef" name="styleCode" label="69码" v-model:keyValue="queryParams.styleCode"
                :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'" :disabled="mechanism || fiveMechanism" :rules="[
                    { validator: validatorStyleCode, message: '请输入正确内容' },
                ]" />
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="tradeMode" label="贸易方式"
                    v-model="queryParams.tradeMode" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择贸易方式' },
                    ]" :disabled="mechanism || fiveMechanism">
                    <template #input>
                        <van-radio-group v-model="tradeModeChecked" direction="horizontal">
                            <van-radio v-for="item in tradeModeColumns" :key="item.value" :name="item.value">{{
                                item.text }}</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
            </van-cell-group>
            <!-- <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="ingredient" label="材质"
                    v-model="queryParams.ingredient" placeholder="请输入" maxlength="50" :rules="[
                        { required: false, trigger: 'onBlur', message: '请输入材质名称' }
                    ]" @input="(e) => { forbidRule(e, 'ingredient', 'emoji') }" />
            </van-cell-group> -->
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="specs" label="规格/材质"
                    v-model="queryParams.specs" placeholder="请输入" required maxlength="200" :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入规格/材质名称' }
                    ]" @input="(e) => { forbidRule(e, 'specs', 'emoji') }" />
            </van-cell-group>
            <formNumberKeyboard :formRef="formRef" name="tax" label="平台扣点" v-model:keyValue="queryParams.tax"
                placeholder="请输入" required :disabled="correctMechanism || fiveMechanism" :rules="[
                    { required: true, trigger: 'onBlur', message: '请输入平台扣点' },
                    {
                        validator: validatorcommission,
                        message: '请输入正确内容：整数或者保留两位小数',
                    },
                ]" extraKey=".">
                <div style="display: flex;align-items: center;">
                    <span style="margin-right: 5px;">%</span>
                    <PointButton @onClick="isPoint = true" />
                </div>
            </formNumberKeyboard>
            <div>
                <div class="mechanism_title">机制一</div>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="cooperationMode" label="合作方式"
                        v-model="queryParams.cooperationMode" readonly placeholder="请选择" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择合作方式' },
                        ]">
                        <template #input>
                            <van-radio-group :disabled="correctMechanism || fiveMechanism"
                                v-model="queryParams.cooperationMode" direction="horizontal">
                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                    :name="item.value">{{
                                        item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism" label="机制"
                        maxlength="12" v-model="queryParams.liveStreamingMechanism"
                        :disabled="correctMechanism || fiveMechanism"
                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism', 'blank') }" placeholder="请输入" required
                        :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入机制' },
                        ]" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode == '分佣'" name="price"
                    label="售价" :disabled="correctMechanism || fiveMechanism" v-model:keyValue="queryParams.price"
                    placeholder="请输入" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入售价' },
                        {
                            validator: validatorNumber,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />

                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode == '分佣'" name="commission"
                    label="佣金" v-model:keyValue="queryParams.commission" placeholder="请输入"
                    :disabled="correctMechanism || fiveMechanism" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入佣金' },
                        {
                            validator: validatorcommission,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode == '分佣'"
                    :disabled="correctMechanism || fiveMechanism" name="brokerage" label="补充佣金"
                    v-model:keyValue="queryParams.brokerage"
                    :placeholder="(correctMechanism || fiveMechanism) ? '' : '请输入'" :rules="[
                        {
                            validator: validatorbrokerage,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>

                <van-cell-group inset v-if="queryParams.cooperationMode == '分佣'">
                    <van-field input-align="right" error-message-align="right" name="costPrice" label="成本"
                        v-model="queryParams.costPrice" readonly required placeholder="请输入" />
                </van-cell-group>
                <formNumberKeyboard v-else :formRef="formRef" name="costPrice" label="成本"
                    :disabled="correctMechanism || fiveMechanism" v-model:keyValue="queryParams.costPrice"
                    placeholder="请输入" :required="queryParams.cooperationMode == '供货'" :rules="[
                        {
                            validator: validatorNumbercostPrice,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />
                <div class="add_mechanism" @click="addMechanism(2)"
                    v-if="mechanismArr.length == 1 && !correctMechanism && !fiveMechanism">
                    <van-image :src="tianjia"></van-image>
                    <div class="title">添加机制</div>
                </div>
            </div>
            <div v-if="mechanismArr.indexOf(2) !== -1">
                <div class="mechanism_title">
                    机制二
                    <div class="delete_mechanism" @click="deleteMechanism(2)"
                        v-if="!correctMechanism && !fiveMechanism">
                        <van-image :src="shanchu"></van-image>
                        <div class="title">删除机制</div>
                    </div>
                </div>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="cooperationMode2" label="合作方式"
                        v-model="queryParams.cooperationMode2" readonly placeholder="请选择" clearable :rules="[
                            { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                        ]">
                        <template #input>
                            <van-radio-group :disabled="correctMechanism || fiveMechanism"
                                v-model="queryParams.cooperationMode2" direction="horizontal">
                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                    :name="item.value">{{
                                        item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism2" label="机制"
                        :disabled="correctMechanism || fiveMechanism" maxlength="12"
                        v-model="queryParams.liveStreamingMechanism2" :required="!!queryParams.cooperationMode2"
                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism2', 'blank') }" placeholder="请输入" :rules="[
                            { validator: validators2, message: '请输入机制' },
                        ]" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode2 == '分佣'" name="price2"
                    label="售价" v-model:keyValue="queryParams.price2" placeholder="请输入"
                    :disabled="correctMechanism || fiveMechanism" :required="queryParams.cooperationMode2 == '分佣'"
                    :rules="[
                        { validator: validators2, message: '请输入售价' },
                        {
                            validator: validatorNumber2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />

                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode2 == '分佣'" name="commission2"
                    label="佣金" v-model:keyValue="queryParams.commission2" placeholder="请输入"
                    :required="queryParams.cooperationMode2 == '分佣'" :disabled="correctMechanism || fiveMechanism"
                    :rules="[
                        { validator: validators2, message: '请输入佣金' },
                        {
                            validator: validatorcommission2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode2 == '分佣'" name="brokerage2"
                    :disabled="correctMechanism || fiveMechanism" label="补充佣金" v-model:keyValue="queryParams.brokerage2"
                    :placeholder="(correctMechanism || fiveMechanism) ? '' : '请输入'" :rules="[
                        {
                            validator: validatorbrokerage2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>

                <van-cell-group inset v-if="queryParams.cooperationMode2 == '分佣'">
                    <van-field input-align="right" error-message-align="right" name="costPrice2" label="成本"
                        v-model="queryParams.costPrice2" readonly required placeholder="请输入" />
                </van-cell-group>
                <formNumberKeyboard v-else :formRef="formRef" name="costPrice2" label="成本"
                    :disabled="correctMechanism || fiveMechanism" v-model:keyValue="queryParams.costPrice2"
                    placeholder="请输入" :required="queryParams.cooperationMode2 == '供货'" :rules="[
                        {
                            validator: validatorNumbercostPrice2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />
                <div class="add_mechanism" @click="addMechanism(3)"
                    v-if="mechanismArr.length == 2 && !correctMechanism && !fiveMechanism">
                    <van-image :src="tianjia"></van-image>
                    <div class="title">添加机制</div>
                </div>
            </div>
            <div v-if="mechanismArr.indexOf(3) !== -1">
                <div class="mechanism_title">
                    机制三
                    <div class="delete_mechanism" @click="deleteMechanism(3)"
                        v-if="!correctMechanism && !fiveMechanism">
                        <van-image :src="shanchu"></van-image>
                        <div class="title">删除机制</div>
                    </div>
                </div>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="cooperationMode3" label="合作方式"
                        v-model="queryParams.cooperationMode3" readonly placeholder="请选择" :rules="[
                            { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                        ]">

                        <template #input>
                            <van-radio-group :disabled="correctMechanism || fiveMechanism"
                                v-model="queryParams.cooperationMode3" direction="horizontal">
                                <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                    :name="item.value">{{
                                        item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism3" label="机制"
                        :disabled="correctMechanism || fiveMechanism" maxlength="12"
                        v-model="queryParams.liveStreamingMechanism3" :required="!!queryParams.cooperationMode3"
                        @input="(e) => { forbidRule(e, 'liveStreamingMechanism3', 'blank') }" placeholder="请输入" :rules="[
                            { validator: validators3, message: '请输入机制' },
                        ]" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode3 == '分佣'" name="price3"
                    label="售价" v-model:keyValue="queryParams.price3" placeholder="请输入"
                    :required="queryParams.cooperationMode3 == '分佣'" :disabled="correctMechanism || fiveMechanism"
                    :rules="[
                        { validator: validators3, message: '请输入售价' },
                        {
                            validator: validatorNumber2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />

                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode3 == '分佣'" name="commission3"
                    label="佣金" :disabled="correctMechanism || fiveMechanism" v-model:keyValue="queryParams.commission3"
                    placeholder="请输入" :required="queryParams.cooperationMode3 == '分佣'" :rules="[
                        { validator: validators3, message: '请输入佣金' },
                        {
                            validator: validatorcommission2,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>
                <formNumberKeyboard :formRef="formRef" v-if="queryParams.cooperationMode3 == '分佣'" name="brokerage3"
                    :disabled="correctMechanism || fiveMechanism" label="补充佣金" v-model:keyValue="queryParams.brokerage3"
                    :placeholder="(correctMechanism || fiveMechanism) ? '' : '请输入'" :rules="[
                        {
                            validator: validatorbrokerage3,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    %
                </formNumberKeyboard>

                <van-cell-group inset v-if="queryParams.cooperationMode3 == '分佣'">
                    <van-field input-align="right" error-message-align="right" name="costPrice3" label="成本"
                        v-model="queryParams.costPrice3" readonly required placeholder="请输入" />
                </van-cell-group>
                <formNumberKeyboard v-else :formRef="formRef" name="costPrice3" label="成本"
                    :disabled="correctMechanism || fiveMechanism" v-model:keyValue="queryParams.costPrice3"
                    placeholder="请输入" :required="queryParams.cooperationMode3 == '供货'" :rules="[
                        {
                            validator: validatorNumbercostPrice3,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey="." />
            </div>

            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="discountPrice" label="能否破价"
                    v-model="queryParams.discountPrice" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择能否破价' },
                    ]" :disabled="mechanism || fiveMechanism">
                    <template #input>
                        <van-radio-group v-model="discountPriceChecked" direction="horizontal">
                            <van-radio v-for="item in discountPriceColumns" :key="item.value" :name="item.value">{{
                                item.text }}</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset v-if="hm_warehouse_show">

                <van-field input-align="right" error-message-align="right" name="warehouse" label="走仓" required :rules="[
                    { required: true, trigger: 'onBlur', message: '请选择是否走仓' },
                ]" v-model="queryParams.warehouse">
                    <template #input>
                        <van-radio-group v-model="warehouseChecked" direction="horizontal">
                            <van-radio v-for="item in discountWarehouse" :key="item.value" :name="item.value">{{
                                item.text }}</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>

            </van-cell-group>
            <formNumberKeyboard :formRef="formRef" name="historyPrice" label="历史最低售价"
                v-model:keyValue="queryParams.historyPrice" :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'"
                :disabled="mechanism || fiveMechanism" :rules="[
                    {
                        required: false,
                        trigger: 'onBlur',
                        message: '请输入历史最低售价',
                    },
                    {
                        validator: validatorPrice,
                        message: '请输入正确的历史最低售价',
                    },
                ]" extraKey="." />
            <van-cell-group inset>
                <van-field v-model="queryParams.sellingPoints" input-align="right" error-message-align="right" rows="1"
                    autosize maxlength="189" label="卖点" @input="(e) => { forbidRule(e, 'sellingPoints', 'emoji') }"
                    name="sellingPoints"
                    placeholder="请输入卖点" required :rules="[
                        { validator: validSpace, message: '请输入卖点' }
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field v-model="queryParams.groupName" input-align="right" error-message-align="right"
                    maxlength="20" autosize label="对接群名" @input="(e) => { forbidRule(e, 'groupName', 'emoji') }"
                    placeholder="请输入对接群名" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="deliveryTime" label="发货时间"
                    v-model="queryParams.deliveryTime" placeholder="请输入发货时间" maxlength="48"
                    :disabled="mechanism || fiveMechanism" @input="(e) => { forbidRule(e, 'deliveryTime', 'emoji') }"
                    required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入发货时间' }
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="eligibility" label="发货地"
                    v-model="queryParams.placeDelivery" placeholder="请输入发货地" maxlength="100"
                    @input="(e) => { forbidRule(e, 'placeDelivery', 'emoji') }" />
                <!-- <van-field v-model="queryParams.placeDelivery" is-link readonly input-align="right"
                    error-message-align="right" name="placeDelivery" label="发货地" placeholder="点击选择省市区"
                    @click="popupClcik(() => showBusinessAddress = true)" />
                <van-popup v-model:show="showBusinessAddress" position="bottom">
                    <van-area title="发货地" :area-list="areaList" @confirm="onConfirmBusinessAddress"
                        @cancel="showBusinessAddress = false" v-model="queryParams.placeDeliveryId" />
                </van-popup> -->
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="logistics" label="物流/快递" :rules="[
                    { required: false, trigger: 'onBlur', message: '请输入商品物流/快递' },
                ]" v-model="queryParams.logistics" :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'"
                    maxlength="20" :disabled="mechanism || fiveMechanism"
                    @input="(e) => { forbidRule(e, 'logistics', 'emoji') }" />
            </van-cell-group>

            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="eligibility" label="适用人群"
                    v-model="queryParams.eligibility" :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'"
                    :disabled="mechanism || fiveMechanism" maxlength="20"
                    @input="(e) => { forbidRule(e, 'eligibility', 'emoji') }" />
            </van-cell-group>
            <formNumberKeyboard :formRef="formRef" name="factoryStockNum" label="厂家可用库存"
                v-model:keyValue="queryParams.factoryStockNum" placeholder="请输入" maxlength="8" required :rules="[
                    { required: true, trigger: 'onBlur', message: '请输入厂家可用库存' }
                ]" :disabled="mechanism || fiveMechanism" />
            <van-cell-group inset>
                <van-field v-model="queryParams.noSendArea" input-align="right" error-message-align="right"
                    maxlength="72" rows="1" autosize label="不发货地区"
                    :placeholder="(mechanism || fiveMechanism) ? '-' : '请输入'"
                    @input="(e) => { forbidRule(e, 'noSendArea', 'emoji') }" :disabled="mechanism || fiveMechanism" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="bigDate" label="大货时间" v-model="queryParams.bigDate" is-link input-align="right"
                    error-message-align="right" readonly placeholder="请选择" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择大货时间' }
                    ]" @click="popupClcik(() => showDeliveryTime = true)" />
                <van-popup v-model:show="showDeliveryTime" position="bottom">
                    <van-date-picker @confirm="onConfirmBottom" @cancel="showDeliveryTime = false"
                        v-model="currentDateBottom" :min-date="minDate" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="isPackageRemind" label="包销提醒" input-align="right" error-message-align="right">
                    <template #input>
                        <van-switch v-model="queryParams.isPackageRemind" />
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="packageDeadline" label="包销时限" v-model="queryParams.packageDeadline" is-link
                    input-align="right" error-message-align="right" readonly placeholder="请选择"
                    @click="showUnderwritingTimes = true" />
                <van-popup v-model:show="showUnderwritingTimes" position="bottom">
                    <van-picker title="选择包销时限" :columns="underwritingTimesColumns" @confirm="onConfirmUnderwritingTimes"
                        @cancel="showUnderwritingTimes = false" />
                </van-popup>
            </van-cell-group>

            <div class="image-title">
                <div class="require_icon">*</div>
                无AB货截图
            </div>
            <van-cell-group inset>
                <van-field name="无AB货截图" label="" v-model="queryParams.noAbImage" :rules="[
                    { required: true, trigger: 'onBlur', message: '请上传无AB货截图' }
                ]">
                    <template #input>
                        <div class="value">
                            <draggable class='dragge_box' :list="abImageList" ghost-class="ghost"
                                chosen-class="chosenClass" animation="300" :delay="300" @start="onStart" @end="onEnd">
                                <template #item="{ element, index }">
                                    <div class="imgList">
                                        <div class="loading_pic" v-if="!element.url">
                                            <van-loading type="spinner" size="20" />
                                        </div>
                                        <van-image v-if="element.url"
                                            :src="element.url + '?x-oss-process=image/resize,w_300'"
                                            @click="enlargeImage(element.url)" width="90px" height="90px"></van-image>
                                        <van-icon name="cross" color="#fff"
                                            v-if="!mechanism && !fiveMechanism && element.url" @click.prevent="
                                                deleteImg(
                                                    abImageList,
                                                    index,
                                                )
                                                " />
                                    </div>
                                </template>
                            </draggable>
                            <van-image width="90px" height="90px" :src="upload" v-if="abImageList.length < 1"
                                @click="postImages('noAbImage', 1)" v-throttle:click></van-image>
                        </div>
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title">
                大货视频
            </div>
            <van-cell-group inset>
                <van-field name="大货视频" label="" v-model="queryParams.bigVideo">
                    <template #input>
                        <div class="value">
                            <draggable class='dragge_box' :list="productVideoList" ghost-class="ghost"
                                chosen-class="chosenClass" animation="300" :delay="300" @start="onStart" @end="onEnd">
                                <template #item="{ element, index }">
                                    <div class="imgList">
                                        <div class="loading_pic" v-if="!element.url">
                                            <van-loading type="spinner" size="20" />
                                        </div>
                                        <VideoDisplay :src="element.url" v-if="element.url" />
                                        <van-icon name="cross" class="delete_icon" v-if="element.url" color="#fff"
                                            @click.prevent="
                                                deleteImg(
                                                    productVideoList,
                                                    index,
                                                )
                                                " />
                                    </div>
                                </template>
                            </draggable>
                            <van-image width="90px" height="90px" :src="upload" v-if="productVideoList.length < 1"
                                @click="postVideo('bigVideo', 1)" v-throttle:click></van-image>
                        </div>
                    </template>
                </van-field>
            </van-cell-group>

            <div class="image-title">商品图</div>
            <van-cell-group inset>
                <van-field name="商品图" label="" v-model="queryParams.productImage">
                    <template #input>
                        <UpLoadDom :arr="productImageList || []" @deleteClick="deleteImg"
                            @postImageClick="postImage('productImage', 5)" :max-count="5" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title">备案凭证/行政许可批件</div>
            <van-cell-group inset>
                <van-field name="备案凭证/行政许可批件" label="" v-model="queryParams.voucherImage">
                    <template #input>
                        <UpLoadDom :arr="voucherImageList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism" @postImageClick="postImages('voucherImage', 5)"
                            :max-count="5" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title">
                其他资质
            </div>
            <van-cell-group inset>
                <van-field name="其他资质" label="" v-model="queryParams.otherImage">
                    <template #input>
                        <UpLoadDom :arr="otherImageList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism" @postImageClick="postImages('otherImage', 10)"
                            :max-count="10" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title" v-if="tradeModeChecked == '进口'">
                进口货物/原材料报关单
            </div>
            <van-cell-group inset>
                <van-field name="进口货物/原材料报关单" label="" v-if="tradeModeChecked == '进口'"
                    v-model="queryParams.customsDeclarationImage">
                    <template #input>
                        <UpLoadDom :arr="customsDeclarationImageList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism"
                            @postImageClick="postImages('customsDeclarationImage', 5)" :max-count="5"
                            :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title" v-if="tradeModeChecked == '进口'">
                进口产品备案材料
            </div>
            <van-cell-group inset>
                <van-field name="进口产品备案材料" label="" v-if="tradeModeChecked == '进口'"
                    v-model="queryParams.customsInformationImage">
                    <template #input>
                        <UpLoadDom :arr="customsInformationImageList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism"
                            @postImageClick="postImages('customsInformationImage', 5)" :max-count="5"
                            :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title" v-if="tradeModeChecked == '进口'">
                进口产品原材料检验检疫证明
            </div>
            <van-cell-group inset>
                <van-field name="进口产品原材料检验检疫证明" label="" v-if="tradeModeChecked == '进口'"
                    v-model="queryParams.customsInspectionImage">
                    <template #input>
                        <UpLoadDom :arr="customsInspectionImageList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism" @postImageClick="postImages('customsInspectionImage', 5)"
                            :max-count="5" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title" v-if="tradeModeChecked == '进口'">
                检测报告
            </div>
            <van-cell-group inset>
                <van-field name="检测报告" label="" v-if="tradeModeChecked == '进口'"
                    v-model="queryParams.customsTestReportImgae">
                    <template #input>
                        <UpLoadDom :arr="customsTestReportImgaeList || []" @deleteClick="deleteImg"
                            :look="mechanism || fiveMechanism" @postImageClick="postImages('customsTestReportImgae', 5)"
                            :max-count="5" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div style="width: 100%; bottom: 0">
                <van-button round block :loading="loading" loading-text="执行中..." type="primary" native-type="submit"
                    v-throttle:click>
                    保存
                </van-button>
            </div>
        </van-form>
        <van-dialog v-model:show="appShow" title="发起资质审批" :showConfirmButton="false" class="app_pop">
            <van-image :src="colseImg" @click="close"></van-image>
            <div class="content">
                该商品的资质目前属于审核不通过状态，请确认是否将本次编辑内容报送品控部~
            </div>
            <div class="button" @click="submitted" v-throttle:click>

                <template v-if="loading">
                    <van-loading type="spinner" size="24px" color="#fff"> 执行中...</van-loading>
                </template>
                <template v-else>
                    报送审批
                </template>
            </div>

        </van-dialog>
    </div>
    <SupplierScreen :isShow="showSupplierName" @cancel="showSupplierName = false" @submit="onConfirmSupplierName">
    </SupplierScreen>
    <Point :show="isPoint" v-model:costPrice="queryParams.costPrice" v-model:costPrice2="queryParams.costPrice2"
        v-model:costPrice3="queryParams.costPrice3" :mechanismArr="mechanismArr" :data="queryParams"
        @clone="isPoint = false" />
</template>
<script setup lang="ts">
import VideoDisplay from '@/components/videoDisplay/index.vue'
import {
    getDicts,
    getInfoInvent,
    editByInvent,
    editLive,
    getCategoryList,
} from "@/api/productList/index";
import { computed, ref, onUnmounted, onMounted, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showSuccessToast, showFailToast } from "vant";
import { storeToRefs } from "pinia";
import { loginStore } from "@/store/login";
import { showImagePreview } from "vant";
import { getEnvValue } from "@/utils/index";
import SupplierScreen from '@/components/SupplierScreen/index.vue'
import formNumberKeyboard from "@/components/formNumberKeyboard/index.vue";
import Point from '@/views/addProduct/components/point.vue'
import PointButton from '@/views/addProduct/components/pointButton.vue'
import UpLoadDom from '@/components/isImgPdf/upLoadDom.vue'
import { handleImageUpdate } from '@/utils/handleImageUpdate';
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;
const tianjia = new URL("@/assets/productHome/icon_tianjia1.png", import.meta.url).href;
const shanchu = new URL("@/assets/productHome/icon_shanchu.png", import.meta.url).href;
import draggable from 'vuedraggable';
//拖拽开始的事件
const onStart = () => {
}
//拖拽结束的事件
const onEnd = () => {
}
const store = loginStore();
const formRef = ref()
const { token } = storeToRefs(store);
const loadingShow = ref(true)
const queryParams = ref({
    supplierName: "",
    liveStreamingMechanism: "",
    styleName: "",
    categoryName: "",
    styleCode: "",
    tradeMode: "",
    cooperationMode: "",
    price: "",
    costPrice: "",
    commission: "",
    brokerage: "",
    productCategoryName: "",
    categoryId: "",
    brandName: "",

    cooperationMode2: "",
    price2: "",
    costPrice2: "",
    liveStreamingMechanism2: "",
    commission2: "",
    brokerage2: "",

    cooperationMode3: "",
    price3: "",
    costPrice3: "",
    liveStreamingMechanism3: "",
    commission3: "",
    brokerage3: "",

    supplierId: "",
    discountPrice: "",
    sellingPoints: "",
    productImage: "",
    voucherImage: "",
    otherImage: "",
    customsDeclarationImage: "",
    customsInformationImage: "",
    customsInspectionImage: "",
    customsTestReportImgae: "",
    specs: "",
    // ingredient: "",
    warehouse: "",
    groupName: "",
    deliveryTime: "",
    placeDelivery: "",
    placeDeliveryId: "",
    logistics: "",
    eligibility: "",
    factoryStockNum: "",
    noSendArea: "",
    tax: '',
    historyPrice: "",

    bigDate: "",
    isPackageRemind: "",
    packageDeadline: "",
    noAbImage: "",
    bigVideo: "",
});

const showDeliveryTime = ref(false)
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();
// 当前时间
const currentTime = ref([
    year + "",
    month < 10 ? "0" + month : month + "",
    date < 10 ? "0" + date : date + "",
]);
const currentDateBottom = ref([
    year + "",
    month < 10 ? "0" + month : month + "",
    date < 10 ? "0" + date : date + "",
]);
const loading = ref(false)
const underwritingTimesColumns = ref([
    { text: '3个月', value: '3' },
    { text: '6个月', value: '6' },
    { text: '12个月', value: '12' },
    { text: '永久', value: '0' },
])
const showUnderwritingTimes = ref(false)

const isPoint = ref(false)      // 扣点弹框开关
const router = useRouter();
const productImageList = ref<any[]>([]);
const abImageList = ref<any[]>([]);
const productVideoList = ref<any[]>([]);
const voucherImageList = ref<any[]>([]);
const otherImageList = ref<any[]>([]);
const customsDeclarationImageList = ref<any[]>([]);
const customsInformationImageList = ref<any[]>([]);
const customsInspectionImageList = ref<any[]>([]);
const customsTestReportImgaeList = ref<any[]>([]);

const showSupplierName = ref(false);

/** 包销时限关闭 */
const onConfirmUnderwritingTimes = ({ selectedOptions }) => {
    queryParams.value.packageDeadline = selectedOptions[0]?.text;
    showUnderwritingTimes.value = false;
}

// 机制集合
const mechanismArr = ref([1])

const show = ref(false);
const cascaderValue = ref();
const options = ref();
const tradeModeColumns = ref<any>([]);
const tradeModeChecked = ref()
const cooperationModeColumns = ref<any>([]);
const discountPriceColumns = ref<any>([]);
const discountPriceChecked = ref()
const appShow = ref(false)

watchEffect(() => {
    if (queryParams.value.cooperationMode === '分佣' && queryParams.value.price) {
        let costPrice = Number(queryParams.value.price || 0) * (1 - ((Number(queryParams.value.commission || 0) / 100) + (Number(queryParams.value.brokerage || 0) / 100) + (Number(queryParams.value.tax || 0) / 100)))
        queryParams.value.costPrice = costPrice.toFixed(2)
    }
    if (queryParams.value.cooperationMode2 === '分佣' && queryParams.value.price2) {
        let costPrice2 = Number(queryParams.value.price2 || 0) * (1 - ((Number(queryParams.value.commission2 || 0) / 100) + (Number(queryParams.value.brokerage2 || 0) / 100) + (Number(queryParams.value.tax || 0) / 100)))
        queryParams.value.costPrice2 = costPrice2.toFixed(2)
    }
    if (queryParams.value.cooperationMode3 === '分佣' && queryParams.value.price3) {
        let costPrice3 = Number(queryParams.value.price3 || 0) * (1 - ((Number(queryParams.value.commission3 || 0) / 100) + (Number(queryParams.value.brokerage3 || 0) / 100) + (Number(queryParams.value.tax || 0) / 100)))
        queryParams.value.costPrice3 = costPrice3.toFixed(2)
    }
})
/** 日期选择 */
const onConfirmBottom = () => {
    showDeliveryTime.value = false
    queryParams.value.bigDate = currentDateBottom.value.join("-")
}
// 限制最小可选时间
const minDate = computed(() => {
    return new Date(currentTime.value.join('/'))
})

const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;

// 限制必填情况下空格
const validSpace = (val) => {
    if (val) {
        return !/^[\s]*$/.test(val)
    } else {
        return false
    }
}
const validatorStyleCode = (val) => {
    if (val) {
        return /^[0-9]{3,13}$/.test(val)
    } else {
        return true
    }
};
// 历史最低售价
const validatorPrice = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val)
    } else {
        return true
    }
}
const validatorNumber = (val) =>
    /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);

const validatorNumbercostPrice = (val) => {
    if (queryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (queryParams.value.cooperationMode == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}
// 机制二机制三  分佣时非必填 为空时非必填 供货时必填
const validatorNumbercostPrice2 = (val) => {
    if (queryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (queryParams.value.cooperationMode2 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}

const validatorNumbercostPrice3 = (val) => {
    if (queryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (queryParams.value.cooperationMode3 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}

const validators2 = (value) => {
    if (queryParams.value.cooperationMode2) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validators3 = (value) => {
    if (queryParams.value.cooperationMode3) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validatorNumber2 = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    } else {
        return true
    }
}

const validatorcommission2 = (val) => {
    if (val) {
        return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
    } else {
        return true
    }
}
const validatorcommission = (val) =>
    /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);

const validatorbrokerage = (val) => {
    if (queryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage2 = (val) => {
    if (queryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage3 = (val) => {
    if (queryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}

const validatorNumberBrand = (val) => {
    if (val) {
        return /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
    } else {
        return true
    }
}
// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        queryParams.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        queryParams.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}
import { onBeforeRouteLeave } from 'vue-router'
const loadingback = ref(false)
// 页面离开路由
onBeforeRouteLeave((_to, from, next) => {
    if (from.meta.title == "编辑商品" && loadingback.value == false) {
        // 显示确认对话框
        const confirm = window.confirm('是否退出当前编辑页面，已保存的商品信息将被清空');
        if (confirm) {
            next();
        } else {
            next(false);
        }
    } else {
        next();
    }
});
/** 回退 */
const handleLeft = () => {
    router.back()
}

/** 添加机制 */
const addMechanism = (index: number) => {
    mechanismArr.value.push(index)
}
/** 删除机制 */
const deleteMechanism = (index: number) => {
    // 当机制二删除并且机制三也存在得情况 删除机制三 保留机制二
    if (index == 2 && mechanismArr.value.length == 3) {
        mechanismArr.value.splice(2, 1)
        queryParams.value.cooperationMode2 = queryParams.value.cooperationMode3
        queryParams.value.price2 = queryParams.value.price3
        queryParams.value.costPrice2 = queryParams.value.costPrice3
        queryParams.value.liveStreamingMechanism2 = queryParams.value.liveStreamingMechanism3
        queryParams.value.commission2 = queryParams.value.commission3
        queryParams.value.brokerage2 = queryParams.value.brokerage3

        queryParams.value.cooperationMode3 = ""
        queryParams.value.price3 = ""
        queryParams.value.costPrice3 = ""
        queryParams.value.liveStreamingMechanism3 = ""
        queryParams.value.commission3 = ""
        queryParams.value.brokerage3 = ""
    } else {
        let indexs = mechanismArr.value.indexOf(index)
        mechanismArr.value.splice(indexs, 1)
        if (index == 2) {
            queryParams.value.cooperationMode2 = ""
            queryParams.value.price2 = ""
            queryParams.value.costPrice2 = ""
            queryParams.value.liveStreamingMechanism2 = ""
            queryParams.value.commission2 = ""
            queryParams.value.brokerage2 = ""
        } else if (index == 3) {
            queryParams.value.cooperationMode3 = ""
            queryParams.value.price3 = ""
            queryParams.value.costPrice3 = ""
            queryParams.value.liveStreamingMechanism3 = ""
            queryParams.value.commission3 = ""
            queryParams.value.brokerage3 = ""
        }
    }
}
const route = useRoute();
/** 商品id */
const uniquekey = computed(() => {
    return route.params.id;
});

/** 是否为样品邀约进的编辑 */
const types = computed(() => {
    return route.query.type;
});

/** 编辑只可编辑机制 规格/材质 卖点 商品图 */
const mechanism: any = computed(() => {
    return route.query.mechanism;
});
/** 编辑商品信息，除了机制 */
const correctMechanism: any = computed(() => {
    return route.query.correctMechanism;
});
/** 只可编辑规格/材质 卖点 商品图 */
const fiveMechanism: any = computed(() => {
    return route.query.fiveMechanism;
});

/** 供应商名称关闭 */
const onConfirmSupplierName = (options) => {
    showSupplierName.value = false;
    if (options) {
        queryParams.value.supplierName = options.supplierName
        queryParams.value.supplierId = options.id;
    }
};

/** 多图片并发请求更改 */
const fetchImagesSequentially = async (real_src, productImageList) => {
    for (const item of real_src) {
        productImageList.push({
            url: getEnvValue("VITE_APP_PIC_URL") + item
        });
    }
};
/** 报送审批关闭 */
const close = () => {
    appShow.value = false;
}
/** 报送审批提交 */
const submitted = () => {
    loading.value = true
    try {
        showSuccessToast({ type: "success", message: "报送审批成功" });
        loading.value = false
        appShow.value = false;
        router.back();
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('报送审批失败');
        }
        loading.value = false
    }
}
/** 获取详情 */
const getDetail = async () => {

    loadingShow.value = true
    const res = await getInfoInvent({ id: uniquekey.value as any });
    if (types.value) {
        res.data.productImage ?? "";
        res.data.voucherImage ?? "";
        res.data.otherImage ?? "";
        res.data.customsDeclarationImage ?? "";
        res.data.customsInformationImage ?? "";
        res.data.customsInspectionImage ?? "";
        res.data.customsTestReportImgae ?? "";
    }
    if (res.data.productImage) {
        const real_src = res.data.productImage.split(",");
        fetchImagesSequentially(real_src, productImageList.value);
    } else {
        res.data.productImage = "";
    }

    if (res.data.noAbImage) {
        const real_src = res.data.noAbImage.split(",");
        fetchImagesSequentially(real_src, abImageList.value);
    } else {
        res.data.noAbImage = "";
    }

    if (res.data.bigVideo) {
        const real_src = res.data.bigVideo.split(",");
        fetchImagesSequentially(real_src, productVideoList.value);
    } else {
        res.data.bigVideo = "";
    }

    if (res.data.voucherImage) {
        const real_src = res.data.voucherImage.split(",");
        fetchImagesSequentially(real_src, voucherImageList.value);
    } else {
        res.data.voucherImage = "";
    }

    if (res.data.otherImage) {
        const real_src = res.data.otherImage.split(",");
        fetchImagesSequentially(real_src, otherImageList.value);
    } else {
        res.data.otherImage = "";
    }

    if (res.data.customsDeclarationImage) {
        const real_src = res.data.customsDeclarationImage.split(",");
        fetchImagesSequentially(real_src, customsDeclarationImageList.value);
    } else {
        res.data.customsDeclarationImage = "";
    }
    if (res.data.customsInformationImage) {
        const real_src = res.data.customsInformationImage.split(",");
        fetchImagesSequentially(real_src, customsInformationImageList.value);
    } else {
        res.data.customsInformationImage = "";
    }
    if (res.data.customsInspectionImage) {
        const real_src = res.data.customsInspectionImage.split(",");
        fetchImagesSequentially(real_src, customsInspectionImageList.value);
    } else {
        res.data.customsInspectionImage = "";
    }
    if (res.data.customsTestReportImgae) {
        const real_src = res.data.customsTestReportImgae.split(",");
        fetchImagesSequentially(real_src, customsTestReportImgaeList.value);
    } else {
        res.data.customsTestReportImgae = "";
    }


    mechanismArr.value = []
    if (res.data.hmMechanismsList[0].cooperationMode) {
        res.data.hmMechanismsList.forEach((element, index) => {
            if (element.cooperationMode) {
                mechanismArr.value.push(index + 1)
            }
        });
    } else {
        mechanismArr.value.push(1)
    }
    // 贸易方式
    tradeModeChecked.value = res.data.tradeMode
    // 能否破价
    discountPriceChecked.value = res.data.discountPrice
    // 走仓
    warehouseChecked.value = res.data.warehouse
    // 包销提醒
    res.data.isPackageRemind = res.data.isPackageRemind ? true : false
    // 机制1
    res.data.cooperationMode = res.data.hmMechanismsList[0].cooperationMode
    res.data.price = res.data.hmMechanismsList[0].price
    res.data.costPrice = res.data.hmMechanismsList[0].costPrice
    res.data.commission = res.data.hmMechanismsList[0].commission
    res.data.brokerage = res.data.hmMechanismsList[0].brokerage
    res.data.liveStreamingMechanism = res.data.hmMechanismsList[0].liveStreamingMechanism
    // 机制2
    res.data.cooperationMode2 = res.data.hmMechanismsList[1].cooperationMode
    res.data.price2 = res.data.hmMechanismsList[1].price
    res.data.costPrice2 = res.data.hmMechanismsList[1].costPrice
    res.data.commission2 = res.data.hmMechanismsList[1].commission
    res.data.brokerage2 = res.data.hmMechanismsList[1].brokerage
    res.data.liveStreamingMechanism2 = res.data.hmMechanismsList[1].liveStreamingMechanism
    // 机制3
    res.data.cooperationMode3 = res.data.hmMechanismsList[2].cooperationMode
    res.data.price3 = res.data.hmMechanismsList[2].price
    res.data.costPrice3 = res.data.hmMechanismsList[2].costPrice
    res.data.commission3 = res.data.hmMechanismsList[2].commission
    res.data.brokerage3 = res.data.hmMechanismsList[2].brokerage
    res.data.liveStreamingMechanism3 = res.data.hmMechanismsList[2].liveStreamingMechanism

    queryParams.value = res.data;

    cascaderValue.value = queryParams.value.categoryId?.split(',')[queryParams.value.categoryId.split(',').length - 1]
    loadingShow.value = false
};

/** 获取类目 */
const getOptions = async () => {
    try {
        const res = await getCategoryList();
        const processedData = renameField(res.data);
        options.value = processedData;
        await getDetail();
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
};
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
            if (element.children.length === 0) {
                delete element.children;
            }
        }
        return {
            text: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
getOptions();

/** 贸易方式 */
const getTradeMode = async () => {
    const res = await getDicts("hm_trade_type");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    tradeModeColumns.value = res.data;
};
getTradeMode();
/** 合作方式 */
const getcooperationMode = async () => {
    const res = await getDicts("hm_cooperation_mode");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    cooperationModeColumns.value = res.data;
};
getcooperationMode();
/** 能否破价 */
const getDiscountPrice = async () => {
    const res = await getDicts("hm_discount");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    discountPriceColumns.value = res.data;
};
getDiscountPrice();

/** 类目最后选择 */
const onFinish = (value) => {
    show.value = false;
    queryParams.value.productCategoryName = value.selectedOptions
        .map((option) => option.text)
        .join(",");
    queryParams.value.categoryId = value.selectedOptions
        .map((option) => option.value)
        .join(",");
};

/** 类目修改 */
const cascaderShade = ref(false)
const cascaderTimeout = ref()

onUnmounted(() => {
    localStorage.removeItem('queryParams')
    clearTimeout(cascaderTimeout.value)
})
onMounted(() => {

})

/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
const onSubmit = async () => {
    loading.value = true
    const list = JSON.parse(JSON.stringify(queryParams.value));
    list.productImage = getPicByfullPath(productImageList.value)
    list.noAbImage = getPicByfullPath(abImageList.value)
    list.bigVideo = getPicByfullPath(productVideoList.value)
    list.voucherImage = getPicByfullPath(voucherImageList.value)
    list.otherImage = getPicByfullPath(otherImageList.value)
    list.customsDeclarationImage = getPicByfullPath(customsDeclarationImageList.value)
    list.customsInformationImage = getPicByfullPath(customsInformationImageList.value)
    list.customsInspectionImage = getPicByfullPath(customsInspectionImageList.value)
    list.customsTestReportImgae = getPicByfullPath(customsTestReportImgaeList.value)
    // 贸易方式
    list.tradeMode = tradeModeChecked.value
    // 能否破价
    list.discountPrice = discountPriceChecked.value
    // 走仓
    list.warehouse = warehouseChecked.value
    list.isPackageRemind = list.isPackageRemind ? 1 : 0
    if (list.cooperationMode == "供货") {
        delete list.price;
        delete list.commission
        delete list.brokerage
    }
    if (list.cooperationMode2 == "供货") {
        delete list.price2;
        delete list.commission2
        delete list.brokerage2
    }
    if (list.cooperationMode3 == "供货") {
        delete list.price3;
        delete list.commission3
        delete list.brokerage3
    }
    list.hmMechanismsList = [
        { cooperationMode: list.cooperationMode, commission: list.commission, price: list.price, costPrice: list.costPrice, brokerage: list.brokerage, liveStreamingMechanism: list.liveStreamingMechanism },
        { cooperationMode: list.cooperationMode2, commission: list.commission2, price: list.price2, costPrice: list.costPrice2, brokerage: list.brokerage2, liveStreamingMechanism: list.liveStreamingMechanism2 },
        { cooperationMode: list.cooperationMode3, commission: list.commission3, price: list.price3, costPrice: list.costPrice3, brokerage: list.brokerage3, liveStreamingMechanism: list.liveStreamingMechanism3 },
    ]
    if (types.value) {
        try {
            await editLive(list);
            showSuccessToast({ type: "success", message: "修改机制成功" });
            loading.value = false
            loadingback.value = true;
            router.back();
            localStorage.removeItem('queryParams')
        } catch (error) {
            if (error == 'timeout') {
                showFailToast('修改机制失败');
            }
            loading.value = false
        }
    } else {
        try {

            // appShow.value = true
            await editByInvent(list);
            showSuccessToast({ type: "success", message: "修改商品成功" });
            loadingback.value = true;
            loading.value = false
            router.back();
            localStorage.removeItem('queryParams')
        } catch (error) {
            if (error == 'timeout') {
                showFailToast('修改商品失败');
            }
            loading.value = false
        }
    }
};
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
};
// /** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        productImage: productImageList.value,
        voucherImage: voucherImageList.value,
        otherImage: otherImageList.value,
        customsDeclarationImage: customsDeclarationImageList.value,
        customsInformationImage: customsInformationImageList.value,
        customsInspectionImage: customsInspectionImageList.value,
        customsTestReportImgae: customsTestReportImgaeList.value,
        noAbImage: abImageList.value,
        bigVideo: productVideoList.value
    };

    const maxCounts = {
        productImage: 5,
        voucherImage: 5,
        otherImage: 10,
        customsDeclarationImage: 5,
        customsInformationImage: 5,
        customsInspectionImage: 5,
        customsTestReportImgae: 5,
        noAbImage: 1,
        bigVideo: 1
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);

};
/** 商品主图不限制 */
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + "/resource/oss/upload",
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
const postVideo = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "video",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
/** 可上传备案资质，其他资质等 */
const postImages = (name: string, count: number) => {
    if (!mechanism.value && !fiveMechanism.value) {
        (window as any).uni.webView.postMessage({
            data: {
                type: "img",
                count: count,
                name: name,
                url: getEnvValue("VITE_APP_UPLOAD_API") + "/resource/oss/upload",
                header: {
                    Authorization: `Bearer ${token.value}`,
                    clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
                },
            },
        });
    }
};
// const downloadPdf = (item: string) => {
//   (window as any).uni.webView.postMessage({
//     data: {
//       type: 'download',
//       url: item,
//       header: {
//         Authorization: `Bearer ${token.value}`,
//         clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e'
//       }
//     }
//   })
// }
// const isPdf = (url: string) => {
//   return url.includes(".pdf")
// }
/** popup点击事件 */
const popupClcik = (fun: any) => {
    if (!mechanism.value && !fiveMechanism.value) {
        fun()
    }
}


const discountWarehouse = ref([
    {
        value: 1,
        text: '是',
    },
    {
        value: 0,
        text: '否',
    },

]);
const warehouseChecked = ref()


const hm_warehouse_show = computed(() => {

    if (queryParams.value.productCategoryName?.indexOf('饰品') >= 0) {
        return true
    }
    return false
});

</script>
<style lang="less" scoped>
.dragge_box {
    display: contents;
    // align-items: center;
    // flex-wrap: wrap;
}

.cascaderShade {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 9999;
}

:deep(.van-cell:after) {
    display: none;
}

:deep(.van-nav-bar__left .van-icon) {
    color: #1a1b1c !important;
}

:deep(.van-field__label) {
    width: 100px !important;
}

.add_product {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 10px 15px 10px 15px;
    border-radius: 5px;

    .mechanism_title {
        // width: 100%;
        font-weight: 600;
        font-size: 14px;
        color: #1A1B1C;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 15px 10px 15px;

        .delete_mechanism {
            width: 128px;
            height: 34px;
            border-radius: 22px;
            border: 1px solid #FC2540;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: 400;
            font-size: 14px;
            color: #FC2540;

            .van-image {
                width: 14px;
                height: 14px;
            }
        }
    }

    .add_mechanism {
        width: 128px;
        height: 34px;
        border-radius: 22px;
        border: 1px solid #0094FF;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #0094FF;
        margin: auto;

        .van-image {
            width: 14px;
            height: 14px;
        }
    }

    .investmentReview_loading {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;

        .investmentReview_loading_title {
            color: #c8c9cc;
            margin-left: 5px;
        }
    }
}

.app_pop {
    height: 210px !important;
    width: 315px !important;

    .content {
        font-size: 14px;
        color: #000000;
        margin: 20px 0;
    }

    .button {
        background: #0094FF;
        border-radius: 23px;
        font-size: 14px;
        color: #FFFFFF;
        text-align: center;
        height: 36px;
        line-height: 36px;
        margin-bottom: 10px;
    }
}

:deep(.van-dialog__content) {
    padding: 0 16px;
    box-sizing: border-box;

    .van-image {
        position: absolute;
        right: 15px;
        top: 15px;
        width: 10px;
        height: 10px;
    }
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-form) {
    height: 100%;
    overflow-y: scroll;
    background-color: #fff;
    // padding-bottom: 35px !important;
}

.value {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .imgList {
        position: relative;

        .loading_pic {
            width: 90px;
            height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :deep(.van-image__img) {
            margin-right: 5px;
        }

        :deep(.van-icon) {
            position: absolute;
            top: 0;
            z-index: 100;
            right: 0px;
            font-size: 10px;
            height: 15px;
            width: 15px;
            background-color: #000;
            border-bottom-left-radius: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        :deep(.van-icon-cross:before) {
            margin: 0 0 1px 2px;
        }
    }


}

:deep(.van-field__control) {
    color: #b8beca !important;
}

:deep(.van-icon-arrow:before) {
    color: #b8beca !important;
}

.image-title {
    font-weight: 400;
    font-size: 14px;
    color: #1a1b1c;
    background-color: #fff;
    padding-left: 16px;
    margin-top: 5px;
    display: flex;

    .require_icon {
        color: #ee0a24;
        margin-right: 2px;
    }
}

:deep(.van-cell:after) {
    border: none !important;
}

.product_image_div_pdf {
    width: 77px;
    height: 77px;
    margin-right: 5px;
    border: 1px dashed #AFB6C3;
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;

    .product_image_div_pdf_buttton {
        color: #0094FF;
    }
}
</style>